package com.myna.csv.extractor;

import com.myna.csv.domain.PropertyStr;
import com.myna.csv.domain.RDCEntity;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import static com.myna.csv.domain.PropertyStr.*;
import static com.myna.csv.initial.InitialProcessor.rdcFilePIPath;

//import static com.myna.csv.extractor.AllFilesEntityExtract.bodyGroupPIFile;
//import static com.myna.csv.extractor.AllFilesEntityExtract.underlyingPIFile;

public class RelationShipPIExtract extends PublicExtractor {
    public static final Logger LOGGER = LogManager.getLogger(RelationShipPIExtract.class);

    public static List<File> filePIPathList = new ArrayList<>();


//    private File underlyingFile = null;
//    private File bodyGroupFile = null;
//    String zip_bodyGroupFileName = null;
//    String zip_underlyingFileName = null;
//    private static String dateStr;
//    private static int file_seq = 1;

    public RelationShipPIExtract() {
//        try {
//            dateStr = DateUtils.formatDate(new Date(), PropertyStr.dateCS_timestampFormat);
//        } catch (ParseException e) {
//            LOGGER.info(e);
//        }
//        String bodyGroupFileName = PropertyStr.bodyGroupFileName + "-" + dateStr + ".csv";
//        String underlyingFileName = PropertyStr.underlyingFileName + "-" + dateStr + ".csv";
//        zip_bodyGroupFileName = PropertyStr.bodyGroupFileName + "-" + dateStr + ".zip";
//        zip_underlyingFileName = PropertyStr.underlyingFileName + "-" + dateStr + ".zip";
//        underlyingFile = setFileTitle(rdcFilePath, underlyingFileName);
//        bodyGroupFile = setFileTitle(rdcFilePath, bodyGroupFileName);


    }

    public void extract(File file) {
        try (InputStream inputStream = new FileInputStream(file)) {
            XMLStreamReader reader1 = openXmlStreamReader(inputStream);
            Boolean flag = isQuoteOrIssue(reader1);
            //close connection
            closeStream(xmlStreamReader, gis, reader1, inputStream);

            if (flag) {
                try (InputStream inputStream1 = new FileInputStream(file)) {
                    XMLStreamReader reader = openXmlStreamReader(inputStream1);
                    doExacter(reader);

                    closeStream(xmlStreamReader, gis, reader, inputStream1);
                }
            }
        } catch (Exception e) {
            LOGGER.info("extract has error", e);
        }
    }

    private void doExacter(XMLStreamReader reader) throws XMLStreamException {
        while (reader.hasNext()) {
            int eventType = reader.next();
            if (XMLStreamConstants.START_ELEMENT == eventType) {
                String localName = reader.getLocalName();
                if ("entity".equals(localName)) {
                    RDCEntity rdcEntity = new RDCEntity();
                    readRDCEntity(rdcEntity, reader);

                    Long PI = -1L;
                    Boolean flag;
                    try {
                        PI = rdcEntity.getPi();
                        if (rdcEntity.getType().equals("O")) {
                            flag = readPIFile(bodyGroupPIFlag, PI);
                            if (flag) {
                                writeToCSVFile(PI, rdcEntity, bodyGroupFlag);
//                                zipFile(bodyGroupFile, zip_bodyGroupFileName);
//                                delFile(bodyGroupFile);
                            }
                        } else {
                            flag = readPIFile(underlyingPIFlag, PI);
                            if (flag) {
                                writeToCSVFile(PI, rdcEntity, underlyingFlag);
//                                zipFile(underlyingFile, zip_underlyingFileName);
//                                delFile(underlyingFile);
                            }
                        }
                    } catch (Exception ex) {
                        LOGGER.error("The PI is exist,and it's :" + rdcEntity.getPi(), ex);
                    }
                }
            }
        }
    }

    private Boolean readPIFile(String flag, Long pi) {
        int index = 0;
        String folderPath = null;
        if ("UNDERLYINGPI".equals(flag)) {
            folderPath = rdcFilePIPath + PropertyStr.UNDERLYINGPI_FOLDER;
        } else if ("BODYGROUPPI".equals(flag)) {
            folderPath = rdcFilePIPath + PropertyStr.BODYGROUPPI_FOLDER;
        }

        File file = new File(folderPath);


//        final File file = getFilePIList(file);
//
//        while (index < filePIPathList.size()) {
//            file = filePIPathList.get(index);
//            index++;
//
//            reault = ;
//        }
        Boolean result = readZipFile(getFilePIList(file), pi);
        return result;
    }

    public Boolean readZipFile(File file, Long pi) {
        InputStream in = null;
        ZipInputStream zin = null;
        ZipEntry zipEntry;
        BufferedReader br = null;
        try {
            ZipFile zipFile = new ZipFile(file);
            in = new BufferedInputStream(new FileInputStream(file));
            zin = new ZipInputStream(in, Charset.forName("UTF-8"));

            while ((zipEntry = zin.getNextEntry()) != null) {
                if (zipEntry.isDirectory()) {
                } else {
                    if (zipEntry.toString().endsWith(".csv")) {
                        br = new BufferedReader(
                                new InputStreamReader(zipFile.getInputStream(zipEntry)));
                        String line;
                        while ((line = br.readLine()) != null) {
                            if (pi.toString().equals(line.replace("\"", ""))) {
                                return true;
                            }
                        }
                        br.close();
                    }
                }
            }
            zin.closeEntry();
            in.close();
        } catch (Exception e) {
            LOGGER.info("read zip File PI error", e);
        } finally {
            if (!Objects.isNull(br)) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (!Objects.isNull(zin)) {
                try {
                    zin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (!Objects.isNull(in)) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    public File getFilePIList(File file) {
        File[] filePaths = file.listFiles();
        for (File file1 : filePaths) {
            if (file1.isDirectory()) {
                getFilePIList(file1);
            } else if (file1.isFile() && file1.getName().lastIndexOf(".zip") != -1) {
                return file1;
            }
        }
        return null;
    }


//    private Boolean readPIFile(File file, Long pi) {
//        String filePath = rdcFilePIPath + file.getName();
//        CsvReader reader = null;
//        String[] stringList;
//        try {
//            reader = new CsvReader(filePath);
//            while (reader.readRecord()) {
//                stringList = reader.getValues();
//                //stringList[0] PI value
//                if (stringList[0].equals(String.valueOf(pi))) {
//                    return true;
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (reader != null) {
//                reader.close();
//            }
//        }
//        return false;
//    }

    private Boolean isQuoteOrIssue(XMLStreamReader reader) throws XMLStreamException {
        while (reader.hasNext()) {
            int eventType = reader.next();
            if (XMLStreamConstants.START_ELEMENT == eventType && "entity".equals(reader.getLocalName())) {
                String type = reader.getAttributeValue("", "type");
                if ("Q".equals(type) || "O".equals(type)) {
                    return true;
                }
            }
        }
        return false;
    }
}
